<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandHandle">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态">
                <template #default="scope">
                  <el-tag :type="formatInfoType(scope.row.status)">
                    {{ formatStatus(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text">续租</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status === 3"
                    @click="outRent(scope.row.id)"
                  >退租</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="!(scope.row.status === 3)"
                    @click="delRent(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" prop="id" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button
              size="mini"
              type="text"
              @click="$router.push(`/exterpriseDetail?id=${scope.row.id}`)"
            >查看</el-button>
            <el-button size="mini" type="text" @click="editRent(scope.row.id)">编辑</el-button>
            <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="deleteRent(scope.row.id)">
              <el-button slot="reference" size="mini" type="text" style="margin-left:10px;">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleSizeChange"
      />
    </div>
    <!-- 弹窗区域 -->
    <el-dialog title="添加合同" :visible="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload action="#" :file-list="fileList" :http-request="uploadRequest" :before-upload="beforeUpload">
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getEnterpriseListAPI, deleteEnterpriseAPI, getBuildingListAPI, uploadLicenseAPI, addContractAPI, getRentListAPI, outRentAPI, delRentAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      params: {
        page: 1,
        name: '',
        pageSize: 10
      },
      list: [],
      total: 0,
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      buildList: [],
      fileList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const res = await getEnterpriseListAPI(this.params)
      this.list = res.data?.rows.map((item) => {
        return {
          ...item,
          rentList: [] // 每一行补充存放合同的列表
        }
      })
      this.total = res.data?.total
    },
    handleSizeChange(page) {
      this.params.page = page
      this.getList()
    },
    doSearch() {
      this.params.page = 1
      this.getList()
    },
    editRent(id) {
      this.$router.push({
        path: '/enterpriseAdd',
        query: {
          id
        }
      })
    },
    async deleteRent(id) {
      await deleteEnterpriseAPI(id)
      this.$message.success('删除成功')
      this.getList()
    },
    // 打开弹窗
    async addRent(id) {
      this.rentDialogVisible = true
      // 获取楼宇下拉列表
      const res = await getBuildingListAPI(this.rentForm)
      this.buildList = res.data
      // 把企业id存入表单对象
      this.rentForm.enterpriseId = id
    },
    // 关闭弹窗
    closeDialog() {
      this.rentDialogVisible = false
    },
    // async getBuildingList() {
    //   const res = await getBuildingListAPI(this.rentForm)
    //   this.rentForm = res.data
    // }
    beforeUpload(file) {
      const isDOC = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      const isPDF = file.type === 'application/pdf'
      if (!isDOC && !isPDF) {
        this.$message.error('上传文件只能是 doc/pdf 格式!')
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return isDOC || isPDF && isLt5M
    },
    async uploadRequest(data) {
      // 检查文件是否存在
      if (!data || !data.file) {
        this.$message.error('未提供文件，请选择文件后再尝试上传。')
        return
      }
      const file = data.file
      const allowedTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword']
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('文件类型不支持，仅支持 PDF、Word 文档格式。')
        return
      }

      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')

      try {
        const res = await uploadLicenseAPI(formData)
        // 检查服务器返回的数据结构是否符合预期
        if (res && res.data && res.data.id && res.data.url) {
          this.rentForm.contractId = res.data.id
          this.rentForm.contractUrl = res.data.url
          this.buildList.push({ name: file.name, url: res.data.url })
          this.$message.success('上传成功')
        } else {
          this.$message.error('服务器返回数据不完整，请联系管理员。')
        }
      } catch (error) {
        // 提供更详细的错误信息
        this.$message.error(`上传失败：${error.message}，请重试或联系管理员。`)
        console.error(error)
      }
    },
    // 确定提交
    async confirmAdd() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
          // 确保 rentTime 是一个有效的数组，并且有开始和结束时间
          if (!this.rentForm.rentTime || !Array.isArray(this.rentForm.rentTime) || this.rentForm.rentTime.length !== 2) {
            this.$message.error('请选择租赁起止日期')
            return
          }

          const startTime = this.rentForm.rentTime[0]
          const endTime = this.rentForm.rentTime[1]

          await addContractAPI({
            buildingId,
            contractId,
            contractUrl,
            enterpriseId,
            type,
            startTime,
            endTime
          })

          // 更新列表
          this.getList()
          // 关闭弹框
          this.rentDialogVisible = false
          // 重置表单
          this.$refs.addForm.resetFields()
          this.rentForm.contractUrl = ''
          this.rentForm.contractId = ''
          this.contractList = []
        }
      })
    },
    // 只有展开时获取数据并绑定
    // row: 当前展开那行表格的数据对象
    // rows：当前已展开的所有行表格的数据对象的集合
    async expandHandle(row, rows) {
      // rows 中包含当前展开行数据，说明是展开状态
      const isExpend = rows.find(item => item.id === row.id)
      // 因为展开/关闭都会触发此事件函数，做个判断只有展开时获取数据
      if (isExpend) {
        const res = await getRentListAPI(row.id)
        res.data.forEach(obj => {
          row.rentList.push(obj)
        })
      } else {
        // 关闭时，把当前行的合同列表清空，防止下次打开时不断 push 叠加
        row.rentList.splice(0)
      }
    },
    // 格式化 tag 类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 格式化 status
    formatStatus(type) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[type]
    },
    outRent(rentId) {
      this.$confirm('确认退租吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 1. 调用接口
        await outRentAPI(rentId)
        // 2. 重新拉取列表
        this.getList()
        this.$message({
          type: 'success',
          message: '退租成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除合同
    delRent(id) {
      this.$confirm('确认删除此合同吗吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 1. 调用接口
        await delRentAPI(id)
        // 2. 重新拉取列表
        this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
